//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useDragonFlyStores } from "./store";
import type { MemberInfo } from "@/api/dragonfly/member";
import { list as list_dragonfly_member, remove as remove_dragonfly_member } from "@/api/dragonfly/member";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { list_member as list_project_member } from "@/api/project_member";
import { gen_access_token } from "@/api/project_server";
import { Button, message, Space, Table, Tag } from "antd";
import type { ColumnsType } from 'antd/lib/table';
import UserPhoto from "@/components/Portrait/UserPhoto";
import UpdatePermModal from "./components/UpdatePermModal";


const MemberPanel = () => {
    const appStore = useDragonFlyStores();

    const [validMemberUserIdList, setValidMemberUserIdList] = useState<string[]>([]);
    const [memberList, setMemberList] = useState<MemberInfo[]>([]);
    const [updateMemberInfo, setUpdateMemberInfo] = useState<MemberInfo | null>(null);


    const loadValidMemberUserIdList = async () => {
        const sessionId = await get_session();
        const res = await request(list_project_member(sessionId, appStore.projectId, false, []));
        setValidMemberUserIdList(res.member_list.map(item => item.member_user_id));
    };

    const loadMemberList = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        const res = await request(list_dragonfly_member(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
        }));
        setMemberList(res.member_list);
    };

    const removeMember = async (memberUserId: string) => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        await request(remove_dragonfly_member(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            member_user_id: memberUserId,
        }))
        await loadMemberList();
        message.info("删除成功");
    };

    const columns: ColumnsType<MemberInfo> = [
        {
            title: "成员",
            width: 100,
            render: (_, row: MemberInfo) => (
                <Space>
                    <UserPhoto logoUri={row.member_logo_uri} style={{ width: "20px", borderRadius: "10px" }} />
                    {row.member_display_name}
                </Space>
            ),
        },
        {
            title: "有效",
            width: 60,
            render: (_, row: MemberInfo) => validMemberUserIdList.includes(row.member_user_id) ? "是" : "否",
        },
        {
            title: "权限",
            render: (_, row: MemberInfo) => (
                <Space style={{ flexWrap: "wrap" }}>
                    {row.perm.change_auth_check && <Tag>密钥验证开关</Tag>}
                    {row.perm.read_auth_secret && <Tag>读取验证密钥</Tag>}
                    {row.perm.manage_auth_secret && <Tag>管理验证密钥</Tag>}
                </Space>
            ),
        },
        {
            title: "操作",
            width: 120,
            render: (_, row: MemberInfo) => (
                <>
                    {validMemberUserIdList.includes(row.member_user_id) == true && (
                        <Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setUpdateMemberInfo(row);
                            }}>设置权限</Button>
                    )}
                    {validMemberUserIdList.includes(row.member_user_id) == false && (
                        <Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                removeMember(row.member_user_id);
                            }}>移除无效成员</Button>
                    )}
                </>
            )
        }
    ];

    useEffect(() => {
        if (appStore.remoteServer != null) {
            loadValidMemberUserIdList();
            loadMemberList();
        }
    }, [appStore.projectId, appStore.remoteServer]);

    return (
        <>
            <Table rowKey="member_user_id" dataSource={memberList} columns={columns} pagination={false} />
            {updateMemberInfo != null && (
                <UpdatePermModal member={updateMemberInfo} onCancel={() => setUpdateMemberInfo(null)}
                    onOk={() => {
                        setUpdateMemberInfo(null);
                        loadMemberList();
                    }} />
            )}
        </>
    );
};

export default observer(MemberPanel);
